<template>
  <div style="height: 100vh; background: #e8e8e8; padding: 10px">
    <div style="text-align: center; font-size: 18px; font-weight: 500; padding: 10px">问题类型编辑</div>
    <div style="padding: 10px; background-color: #fff; border-radius: 7px; font-size: 18px">
      问题大类：{{ this.problemType }}
    </div>
    <van-form id="issuesDetail" @submit="onSubmit" style="background: rgb(232, 232, 232)">
      <!-- <van-field v-model="typeValue" is-link readonly label="大类" placeholder="请选择问题大类" style="margin-bottom: 10px" @click="showPicker = true"> </van-field> -->
      
      <van-uploader v-model="fileList" multiple :after-read="afterRead" @delete="deleteImg" :before-read="beforeRead" preview style="margin-top: 10px;"/>
      <van-field v-model="issuesDetail.remark" rows="3" label="描述" type="textarea" placeholder="请输出问题描述" autosize maxlength="500" show-word-limit />
      <van-button round block type="info" native-type="submit" style="margin-top: 10px">提交</van-button>
    </van-form>

    <van-button round block @click="onBack" style="margin-top: 10px"> 返回 </van-button>
    <!-- <van-popup round v-model:show="showPicker" position="bottom">
      <van-picker show-toolbar :columns="pickerColumns" @cancel="showPicker = false" @confirm="onConfirm"></van-picker>
    </van-popup> -->
  </div>
</template>

<script>
import { Notify } from 'vant'
import { getSealIssuesDetail, updateSealIssues, saveSealIssues, uploadPic, getDictChildList } from '@api/rd/index'

export default {
  components: {},
  data() {
    return {
      showPicker: false,
      fileList: [],
      loading: false,
      issuesDetail: {},
      uploadImage: [],
      id: 0,
      billNo: '',
      problemType: '',
      problemTypePara: '',
      problemTypeList: []
    }
  },
  computed: {
    userInfo() {
      return this.$store.getters.userInfo || null
    }
  },
  mounted() {
    this.getDictChildList('PROBLEM_TYPE', 'problemTypeList')
  },
  created() {
    this.loadData()
  },
  methods: {
    // onConfirm(selectedOptions) {
    //   this.showPicker = false
    //   this.typeValue = selectedOptions.value
    // },
    // onCancel() {
    //   this.showPicker = false
    // },
    // showVanPicker() {
    //   this.showPicker = true
    // },
    async loadData() {
      this.loading = true
      this.billNo = this.$route.query.billNo
      this.problemType = this.$route.query.problemType
      if (this.$route.query.id) {
        this.id = this.$route.query.id
      }
      console.log(this.billNo)
      console.log(this.id)
      if (this.id > 0) {
        const params = {
          billNo: this.billNo,
          id: Number(this.id)
        }
        console.log(params)
        try {
          const res = await getSealIssuesDetail(params)
          if (res.code == 200) {
            this.issuesDetail = res.data
            // this.problemType = this.issuesDetail.problemType
            // this.fileList = this.issuesDetail.imgurl.split('')
            // console.log(this.issuesDetail.imgurl)
            this.issuesDetail.imgurl.forEach(item => {
              const obj = {}
              const name = "url"
              obj[name] = item
              this.fileList.push(obj)
              this.uploadImage.push(obj.url)
            })
            console.log(this.fileList)
          } else {
            if (res.msg) {
              Notify({ type: 'warning', message: res.msg })
            } else {
              Notify({ type: 'warning', message: '获取问题详情失败！' })
            }
          }
        } catch (error) {
          Notify({ type: 'warning', message: '获取问题详情异常！' })
        } finally {
          this.loading = false
        }
      }
    },
    async onSubmit() {
      if (this.id > 0) {
        this.updateSealIssues()
      } else {
        this.saveSealIssues()
      }
    },
    async updateSealIssues() {
      const params = {
        id: this.id,
        billNo: this.billNo,
        // problemType: this.problemType,
        remark: this.issuesDetail.remark,
        imgurl: []
      }
      // console.log(this.problemTypeList)
      this.problemTypeList.forEach( item => {
        if(item.name == this.problemType){
          this.problemTypePara = item.code
        }
      })
      params.problemType = this.problemTypePara
      this.fileList.forEach(item => {
        params.imgurl.push(item.url)
      })
      // console.log(params.imgurl)
      const { realname } = this.userInfo
      params.operator = realname
      console.log(params)
      const res = await updateSealIssues(params)
      try{
        if (res.code == 200) {
          Notify({ type: 'success', message: '更新封样问题成功!' })
          setTimeout(() => {
            this.$router.push({ path: 'sealIssuesList', query: { billNo: this.billNo } })
          }, 1500);
        } else {
          if (res.msg) {
            Notify({ type: 'warning', message: res.msg })
          } else {
            Notify({ type: 'warning', message: '更新封样问题失败!' })
          }
        }
      } catch (error){
        Notify({ type:'warning' , message: '更新封样问题异常!' })
      }
    },
    async saveSealIssues() {
      const params = {
        id: 0,
        billNo: this.billNo,
        // problemType: this.problemType,
        remark: this.issuesDetail.remark,
        imgurl: []
      }
      this.problemTypeList.forEach( item => {
        if(item.name == this.problemType){
          this.problemTypePara = item.code
        }
      })
      params.problemType = this.problemTypePara
      this.uploadImage.forEach(item => {
        params.imgurl.push(item)
        console.log(params.imgurl)
      })
      // params.imgurl = this.uploadImage
      const { realname } = this.userInfo
      params.operator = realname
      console.log(params)
      const res = await saveSealIssues(params)
      if (res.code == 200) {
        Notify({ type: 'success', message: '保存封样问题成功!' })
        // this.onBack()
        setTimeout(() => {
            this.$router.push({ path: 'sealIssuesList', query: { billNo: this.billNo } })
          }, 1500);
      } else {
        if (res.msg) {
          Notify({ type: 'warning', message: res.msg })
        } else {
          Notify({ type: 'warning', message: '保存封样问题失败!' })
        }
      }
    },
    beforeRead(file) {
      if (file instanceof Array && file.length) {
        file.forEach(item => {
          if (item.type !== 'image/jpeg' && item.type !== 'image/png' && item.type !== 'image/jpg') {
            this.$toast.fail('请选择正确图片格式上传')
            return false
          }
        })
        return file
      } else {
        if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/jpg') {
          this.$toast.fail('请选择正确图片格式上传')
          return false
        }
        return file
      }
    },
    async uploadPic(file) {
      file.status = 'uploading'
      file.message = '上传中...'
      let formData = new FormData()
      formData.append('file',file.file)
      formData.append('type',1)
      const res = await uploadPic(formData)
      if(res.code == 200){
        file.status = 'done'
        this.uploadImage.push(res.data.url)
        const index = this.fileList.indexOf(file)
        this.fileList.splice(index,1)
        const obj = {}
        const name = "url"
        obj[name] = res.data.url
        this.fileList.push(obj)
        console.log(this.uploadImage)
      } else {
        file.status = 'failed'
        file.message = '上传失败'
        this.$toast("上传失败!")
      }
    },
    async afterRead(file) {
      console.log(file)
      if (file instanceof Array && file.length) {
        file.forEach(item => {
          this.uploadPic(item)
        })
      } else {
        this.uploadPic(file)
      }
    },
    async getDictChildList(name, list) {
      if (!this[list].length) {
        const params = {
          name: name
        }
        try {
          const res = await getDictChildList('dict', params)
          if (res.code == 200) {
            this[list] = res.data
          } else {
            if (res.msg) {
              Notify({ type: 'warning', message: res.msg })
            } else {
              Notify({ type: 'warning', message: '获取问题类型失败!' })
            }
          }
        } catch (error) {
          Notify({ type: 'warning', message: '获取问题类型异常!' })
        }
      }
    },
    deleteImg(file) {
      // for (let i = 0, len = this.uploadImage.length; i < len; i++) {
      //   if (file.file.name === this.uploadImage[i].name && file.file.size === this.uploadImage[i].size) {
      //     this.uploadImage.splice(i, 1)
      //     break
      //   }
      // }
      // const index = this.uploadImage.indexOf(file.file)
      // console.log(file)
      const index = this.uploadImage.indexOf(file.url)
      // console.log(index)
      this.uploadImage.splice(index, 1)
      console.log(this.uploadImage)
    },
    onBack() {
      // this.$router.push({ path: 'sealIssuesList', query: { billNo: this.billNo } })
      history.back()
    }
  }
}
</script>

